from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import TemplateDoesNotExist
from django.views.generic.simple import direct_to_template #about_pages view
from django.shortcuts import render_to_response
from ktool.models import *
from django import forms
from django.db.models import Q
import string 
import networkx as nx
import pydot
import pylab as pl
#import matplotlib.pyplot as plt
#import matplotlib


class searchform(forms.Form):
    plist=Pathway.objects.all()
    p_options=[(0,'all')]
    for a in plist:
       p_options.append(((a.id),(a.name)))
    orgname=forms.CharField(label="orgname", required=False)
#option for different functions
    inputoptions=[('rlist','submit a reaction list'),('elist','submit an EC number list'),('klist','submit a KO list')]
#option for different results (save or show in the next page), should do it in the result page, choose to save in
#different formats or visualize
#create a temporary file on the server for information transfer between pages    
    input=forms.ChoiceField(label="inoptions", choices=inputoptions,required=False)
    inlist=forms.CharField(label="inlist", required=False)
    pa=forms.MultipleChoiceField(label="select pathways", choices=p_options, initial=0,required=False)
    file  = forms.FileField(initial='c:\test.txt')
#    pa=forms.ChoiceField(label="select pathways", widget=forms.SelectMultiple, choices=p_options)

def search(request):
    if request.method == 'POST':
        f = searchform(request.POST,request.FILES)
        if not f.is_valid():
           err="sth wrong"
           return render_to_response('ksearch.html', locals()) #do sth else 
        else:
           if f.cleaned_data["orgname"]:
                  s=f.cleaned_data["orgname"]
                  orgs=string.split(s,",") #network for merged organisms
                  objs = Reaction.objects.filter(reaorg__org__in=orgs)
 #                 .distinct()
           elif f.cleaned_data["input"]:
              if f.cleaned_data["inlist"]:
                 s=f.cleaned_data["inlist"]
                 ids=string.split(s,",") 
              elif f.cleaned_data["file"]:
#                 s=request.FILES['file'].read()
#                 ids=s.split("\n")
                 ids=[]
                 ss=request.FILES['file'].readlines()
                 for id in ss:
                    if "\n" in id:
                        id=id[:len(id)-2]
                    ids.append(id)
              else:
                err="please enter organism names or submit your own id list!!"
                return render_to_response('ksearch.html', locals())
              if ids:
                 if f.cleaned_data["input"]=="rlist":
                   objs = Reaction.objects.filter(reactionid__in=ids)
                 elif f.cleaned_data["input"]=="elist":
                   objs = Reaction.objects.filter(rea_ec__enzyme__in=ids)
                 else:
                   objs = Reaction.objects.filter(reako__ko__in=ids)
              else:
                err="please enter organism names or submit your own id list!!!"
                return render_to_response('ksearch.html', locals())
           else:
              err="please enter organism names or submit your own id list!"
              return render_to_response('ksearch.html', locals())
#                  objs=Reaction.objects.all()
           if objs:
             if f.cleaned_data["pa"]: 
               if not f.cleaned_data["pa"][0][0]=='0':
                 objs=objs.filter(rea_path__path__in=f.cleaned_data["pa"]).distinct()     
             request.session['r']=objs
             return render_to_response('krea.html', {'reaction_list': objs})
           else:
             err="no reaction found, please check the organism name or your id list!"
             return render_to_response('ksearch.html', locals())
    else:
        f = searchform(request.POST)
        err="please enter organism names or your id list!"
        return render_to_response('ksearch.html', locals())
#generate reaction list for selected organism or selected pathways
#save as text file or SBML, save stoichiometric matrix for flux analysis (later as require determine external mets)
#generate met-link list and visualize
#options for rea list 

class compareform(forms.Form):
    orgname1=forms.CharField(label="orgname", required=False)
    orgname2=forms.CharField(label="orgname", required=False)
    orgname3=forms.CharField(label="orgname", required=False)
    inputoptions=[('rlist','submit a reaction list'),('elist','submit an EC number list'),('klist','submit a KO list')]
    input1=forms.ChoiceField(label="inoptions", choices=inputoptions,required=False)
    file1  = forms.FileField()
    input2=forms.ChoiceField(label="inoptions", choices=inputoptions,required=False)
    file2  = forms.FileField()
    input3=forms.ChoiceField(label="inoptions", choices=inputoptions,required=False)
    file3  = forms.FileField()

def compare(request):
    if request.method == 'POST':
        f = compareform(request.POST,request.FILES)
        if not f.is_valid():
           return render_to_response('kcomp.html', locals()) #do sth else 
        else:
           if f.cleaned_data["orgname1"]:
                  org=f.cleaned_data["orgname1"]
#                  objs1 = Reaction.objects.filter(reaorg__org=org)
                  objs1 = Reaction.objects.filter(reaorg__org=org).values_list('id', flat=True) #return a list of IDs
 #                 .distinct()
           elif f.cleaned_data["input1"]:
               if f.cleaned_data["file1"]:
                 ids1=[]
                 ss=request.FILES['file1'].readlines()
                 for id in ss:
                    if "\n" in id:
                        id=id[:len(id)-2]
                    ids1.append(id)
#                 ids=string.split(s,"\n")
               else:
                err="please enter organism names or submit your own id list!!"
                return render_to_response('ksearch.html', locals())
               if ids1:
                 if f.cleaned_data["input1"]=="rlist":
     #              objs1 = Reaction.objects.filter(reactionid__in=ids)
                   objs1 = ids1 #the list
                 elif f.cleaned_data["input1"]=="elist":
                   objs1 = Reaction.objects.filter(rea_ec__enzyme__in=ids).values_list('id', flat=True)
                 else:
                   objs1 = Reaction.objects.filter(reako__ko__in=ids).values_list('id', flat=True)
               else:
                err="please enter organism names or submit your own id list!!!"
                return render_to_response('ksearch.html', locals())
           else:
              err="please enter organism names or submit your own id list!"
              return render_to_response('ksearch.html', locals())
#                  objs=Reaction.objects.all()
           if objs:
             request.session['r']=objs
             return render_to_response('krea.html', {'reaction_list': objs})
           else:
             err="no reaction found, please check the organism name or your id list!"
             return render_to_response('ksearch.html', locals())
    else:
        f = searchform(request.POST)
        err="please enter organism names or your id list!"
        return render_to_response('ksearch.html', locals())

def rlisttxt(request):
      rf=open('c:/human/media/rlist.txt',"w")
      reas=request.session['r']
      for rea in reas:
        rf.write(rea.reactionid+"\t"+rea.reversibility+"\t"+rea.equation+"\n")
      rf.close()
      rlist=open('c:/human/media/rlist.txt',"rb").read()
      response=HttpResponse(rlist, mimetype="text/plain")
      response['Content-Disposition']='attachment; filename=realist.txt'
      return response

def rlistsbml(request):
   import libsbml as ls
   doc=ls.SBMLDocument(2,1) #version 2 level 3
   m=doc.createModel() #directly give an Id than not necessary to setName
   reas=request.session['r']
   spes=[] #save species names in a list for getting a list without repeat
   cp=m.createCompartment()
   cp.setId("compartment")
   cp.setName(cp.getId())
   for rea in reas:
    r=m.createReaction() #can not use createReaction(rea[0])
#    r.setId(rea.reactionid)
    r.setName(str(rea.reactionid))
    r.setReversible(rea.reversibility=='') 
    a=rea.eq_in_id.split('=')
    subs=a[0].strip().split('+')
    for sub in subs:
        b=sub.strip().split(' ') #coefficient and compound ID seperated by space
        if len(b)==1:
            sto=1.0
            species=str(b[0])
        else:
            sto=float(b[0])
            species=str(b[1])
        sr=r.createReactant() #create a new SpeciesReference object and add as a reactant
        sr.setStoichiometry(sto) # f is a float value
        sr.setSpecies(species) #a string as a species in Model's ListOfSpecies.
        if not species in spes:
            spes.append(species)
            s=m.createSpecies()
            s.setId(species)
            com=Compound.objects.get(compoundid=species)
            s.setName(str(com.name))
            s.setCompartment(cp.getId()) #s is a string for compartment
    pros=a[1].strip().split('+')
    for pro in pros:
        b=pro.strip().split(' ')
        if len(b)==1:
            sto=1.0
            species=str(b[0])
        else:
            sto=float(b[0])
            species=str(b[1])
        sr=r.createProduct() #create a new SpeciesReference object and add as a reactant
        sr.setStoichiometry(sto) # f is a float value
        sr.setSpecies(species) #a string as a species in Model's ListOfSpecies.
        if not species in spes:
            spes.append(species)
            s=m.createSpecies()
            s.setId(species)
            com=Compound.objects.get(compoundid=species)
            s.setName(str(com.name))
            s.setCompartment(cp.getId()) #s is a string for compartment
#   ls.writeSBML(doc,pname+".xml")
#   sbml=open(pname+".xml","rb").read()
   sbml=ls.writeSBMLToString(doc) #not write file on the server
   response=HttpResponse(sbml, mimetype="text/xml")
   response['Content-Disposition']='attachment; filename=reas.xml'
   return response

def metgraph(request):
    reas=request.session['r']
    metlinks=Met_link.objects.filter(rea__in=reas)
    G=nx.MultiDiGraph()
#    Gd = pydot.Dot(graph_type='digraph')
#    mls=[]
    for ml in metlinks:
        rev=ml.rea.reversibility
#        mls.append((ml.com1,ml.com2,ml.rea,rev))
#        mls.append((ml.com1.name,ml.com2.name,ml.rea,rev))
        #Creating a new list with extra columns including information from other tables
        #is one way to transfer multiple table information to the template
        #another way is to creat a function in the model class which returns a value
        #based on data from related table
        #for this case, the best way may be to include the reversibility column in the table
#        G.add_edge(ml.com1,ml.com2)
        G.add_edge(ml.com1.compoundid,ml.com2.compoundid,lable=ml.rea.reactionid)
#        G.add_edge(ml.com1.name,ml.com2.name,lable=ml.rea.reactionid)
#        e=pydot.Edge(ml.com1.name,ml.com2.name,label=ml.rea.reactionid,URL='http://www.kegg.jp/dbget-bin/www_bget?rn:'+ml.rea.reactionid)
#        e=pydot.Edge(ml.com1.name,ml.com2.name)
#        e.set_label(ml.rea.reactionid)
#        e.set_URL('http://www.kegg.jp/dbget-bin/www_bget?rn:'+ml.rea.reactionid)
#        Gd.add_edge(e)
        if not rev:
#          G.add_edge(ml.com1,ml.com2)
          G.add_edge(ml.com2.compoundid,ml.com1.compoundid,lable=ml.rea.reactionid)
#          G.add_edge(ml.com2.name,ml.com1.name,lable=ml.rea.reactionid)
#          e=pydot.Edge(ml.com2.name,ml.com1.name)
#          e.set_label(ml.rea.reactionid)
#          e.set_URL('http://www.kegg.jp/dbget-bin/www_bget?rn:'+ml.rea.reactionid)
#          Gd.add_edge(e)
    nmet=G.number_of_nodes()
    nlink=G.size()
    al=nx.average_shortest_path_length(G)
    UG=G.to_undirected()
#    cluster=nx.average_clustering(UG)
    con=nx.is_connected(UG)
    request.session['mgraph']=G
#    request.session['mgraphdot']=Gd
    return render_to_response('kmetlink.html', locals())

def mgraphvisold(request):
    import pydot
    G=request.session['mgraph']
#    Gd=request.session['mgraphdot']
    Gd=nx.to_pydot(G)
#       nx.write_dot(subG,myfolder+'gws1'+str(i)+'.dot')
#       G=pydot.graph_from_dot_file(myfolder+'gws1'+str(i)+'.dot')
    Gd.write('c:/human/media/mg.svg', prog='dot',format='svg')
    image=open('c:/human/media/mg.svg',"rb").read()
    return HttpResponse(image, mimetype="image/svg+xml")
#    return render_to_response('kmetlink.html', locals())

class netviewform(forms.Form):
    foptions=[('svg','svg'),('png','png'),('gif','gif'),('jpg','jpg')]
#    foptions=[('jpg','jpg'),('png','png'),('gif','gif'),('bmp','bmp'),('svg','svg'),
#              ('dot','dot'),('eps','eps'),('ps','ps'),('pdf','pdf')]
    poptions=[('dot','dot'),('neato','neato'),('twopi','twopi'),('circo','circo'),('fdp','fdp')]
    fformat=forms.ChoiceField(label="format", choices=foptions,required=False)
    prog=forms.ChoiceField(label="program", choices=poptions,required=False)
    rlabel=forms.BooleanField(label="reaction label",required=False)
    mlabel=forms.BooleanField(label="metabolite label",required=False)

def mgraphvis(request):
#    import pydot
    reas=request.session['r']
    metlinks=Met_link.objects.filter(rea__in=reas)
#    Gd = pydot.Dot(graph_type='digraph')
    G = pydot.Dot()
    if request.method == 'GET':
        f = netviewform(request.GET)
        if not f.is_valid():
           return render_to_response('dotviewk.html', {'form': f}) #do sth else 
        else:
           if f.cleaned_data["fformat"]:
              fformat=f.cleaned_data["fformat"]
           else:   
              fformat='svg'
           if f.cleaned_data["prog"]:
              prog=f.cleaned_data["prog"]
           else:   
              prog='dot'
           for link in metlinks:
              e=pydot.Edge(link.com1.name,link.com2.name)
              if f.cleaned_data["rlabel"]:
                 e.set_label(link.rea.reactionid)
              e.set_URL("/kegg/rn/"+link.rea.reactionid)
              e.set_tooltip(link.rea.eq_in_id)
              e.set_labeltooltip(link.rea.equation)
              G.add_edge(e)
           if not f.cleaned_data["mlabel"]:
              s=G.to_string()
              p=s.find('{')
              dotf=open('c:/human/media/mg.dot', 'w')
              dotf.write(s[0:p+1])
              dotf.write('node [label=\"\\N\"];')
              nlist=G.get_node_list()
              for node in nlist:
#                 n=pydot.Node(node.get_name())
#                 n.set_label(" ") #not change at all
#                 G.add_node(n)
                 dotf.write(node.get_name())
              dotf.write(s[p+2:])
              dotf.close()
              G=pydot.graph_from_dot_file('c:/human/media/mg.dot')
           G.write('c:/human/media/mg.'+fformat, prog=prog,format=fformat)
#           if fformat=='svg':
#              image=open('c:/human/media/mg.svg',"rb").read()
#              return HttpResponse(image, mimetype="image/svg+xml")
#           else: 
           return render_to_response("dotviewk.html", {'form': f,'format': fformat})
    
def degdis(request,option):
    import operator #check if this is necessary
    G=request.session['mgraph']
#    deg=G.degree(with_lables=True) #a list or dictionary of node degrees
#maybe easy to convert dic to list
#    dorder=sorted(deg.iteritems(), key=operator.itemgetter(1), reverse=True)
    #iteritems only provide values when requested."key" tells sort based on which element
#or
    if option=="input":
      deg=G.in_degree_iter() #return an iterator directly, saving memory
    elif option=="output":
      deg=G.out_degree_iter() #return an iterator directly, saving memory
    else:
#      dhis=nx.degree_histogram(G) #try this later, a list of degree frequences (0 to max)
#      d=nx.degree(G) #what is the difference between nx.degree(G) and G.degree()
      deg=G.degree_iter() #return an iterator directly, saving memory
    dorder=sorted(deg, key=operator.itemgetter(1), reverse=True)
    dm=dorder[0][1]
    met, d = zip(*dorder)#to transpose a list
#or x2,y2=map(None,*dorder) #None is the function applied
    bin=pl.arange(0,dm+1,1)
    pl.clf()
#    fig=pl.figure()
#    pl.hist(deg,bin,width=1)
    pl.hist(d,bin)
#    pl.savefig(MEDIA_ROOT+"/degreedis.png", dpi=72)
    pl.savefig("c:/human/media/degreedis.png", dpi=72)
    return render_to_response('degree.html', locals())

def centrality(request,option):
    G=request.session['mgraph']
    if option=='closeness':
          c=nx.closeness_centrality(G.to_undirected()).iteritems() #dictionary
    elif option=='betweeness':
          c=nx.betweenness_centrality(G.to_undirected()).iteritems() #dictionary
    elif option=='eccentracity':
          c=nx.eccentricity(G.to_undirected()).iteritems() #need connected network
    elif option=='load':
          c=nx.load_centrality(G.to_undirected()).iteritems()
    elif option=='eigen vector':
          c=nx.eigenvector_centrality(G.to_undirected()).iteritems()
    elif option=='ebetweeness':
          option="edge betweeness"
          c=nx.edge_betweenness(G.to_undirected()).iteritems()
    else:
          option="degree"
          c=nx.degree_centrality(G.to_undirected()).iteritems() #degree centrality by default
    return render_to_response('centrality.html', locals())

def connectivity(request,option):
    G=request.session['mgraph']
    if option=='wcomp':
#      networkx.connected_component_subgraphs(G) #list of graphs
      con=nx.connected_components(G.to_undirected()) #list of list of nodes
      return render_to_response('connectivity.html', locals())
    elif option=='scomp':
#      networkx.strongly_connected_component_subgraphs(G) #list of graphs
      con=nx.strongly_connected_components(G) #list of list of nodes
      return render_to_response('connectivity.html', locals())
    elif option=='bowtie':
      sc=nx.strongly_connected_components(G) #list of list of nodes
      gsc=sc[0]
      n=gsc[0] #select a node in GSC
      outdm=set(nx.single_source_shortest_path_length(G,n).keys())
      indm=set(nx.single_source_shortest_path_length(G.reverse(),n).keys())
      outs=list(outdm-indm) #use sets to find intersection, union and difference between two lists
      ins=list(indm-outdm)
      ns=set(G.nodes())
      isset=list(ns-(indm|outdm))
      return render_to_response('bowtie.html', locals())
    elif option=='indomain':
      con=[]
      for n in G.nodes():
         con.append((n,len(nx.single_source_shortest_path_length(G.reverse(),n))))
#        con.append((n,len(G.predecessors(n)))) #does not work as only calculate directly linked nodes
#        con=nx.all_pairs_shortest_path_length(G.reverse())
      return render_to_response('domain.html', locals())
    elif option=='outdomain':
      con=[]
      for n in G.nodes():
          con.append((n,len(nx.single_source_shortest_path_length(G,n))))
#      con=nx.all_pairs_shortest_path_length(G)
      return render_to_response('domain.html', locals())

def savegraph(request,option):
    G=request.session['mgraph']
    if option=='pajek':
          fname="test.net"
          nx.write_pajek(G, "c:/human/media/"+fname)
    elif option=='dot':
          fname="test.dot"
          Gd=nx.to_pydot(G)
          Gd.write('c:/human/media/'+fname, prog='dot',format='raw')
    elif option=='gml':
          fname="test.gml"
          nx.write_gml(G, "c:/human/media/"+fname)
    elif option=='yaml':
          fname="test.yaml"
          nx.write_yaml(G, "c:/human/media/"+fname)
    else:
          fname="test.txt"
          nx.write_edgelist(G, "c:/human/media/"+fname)
    net=open("c:/human/media/"+fname,"rb").read()
    response=HttpResponse(net, mimetype="text/plain")
    response['Content-Disposition']='attachment; filename='+fname
    return response
    
def keggview(request, op,id): #also show connections between neighbours
    return HttpResponseRedirect("http://www.kegg.jp/dbget-bin/www_bget?"+op+":"+id)

class pathform(forms.Form): #search shortest paths
    com1=forms.CharField(label="source compound", required=False)
    com2=forms.CharField(label="target compound", required=False)

def shortpathold(request): #search shortest paths
    from django.core.exceptions import ObjectDoesNotExist
    if request.method == 'GET':
      f = pathform(request.GET)
      if not f.is_valid():
           err="sth wrong"
           return render_to_response('kpath.html', locals()) #do sth else 
      else:
        c1id=f.cleaned_data["com1"]
        c2id=f.cleaned_data["com2"]
        try:
          c1=Compound.objects.get(compoundid=c1id)
          c2=Compound.objects.get(compoundid=c2id)
        except ObjectDoesNotExist:
          err="can not find the compound, check your id"
          return render_to_response('kpath.html', locals())
#        c1nm=c1.name #when the networkx graph use name rather than IDs
#        c2nm=c2.name
        G=request.session['mgraph']
#        if c1nm in ns and c2nm in ns:
        if c1id in G and c2id in G:
            Gd=pydot.Dot()
            p=nx.shortest_path(G,c1id,c2id)
            for i in range(len(p)-1):
#               G[p[i]][p[i+1]]['lable']
               metlinks=Met_link.objects.filter(com1=p[i]).filter(com2=p[i+1])
               n=pydot.Node(p[i])
               n.set_URL("/kegg/cpd/"+p[i])
               cn=Compound.objects.get(compoundid=p[i]).name
               n.set_tooltip(cn)
               Gd.add_node(n)
               for link in metlinks:
#                 e=pydot.Edge(link.com1.name,link.com2.name)
                 e=pydot.Edge(link.com1.compoundid,link.com2.compoundid)
                 e.set_label(link.rea.reactionid)
                 e.set_URL("/kegg/rn/"+link.rea.reactionid)
                 Gd.add_edge(e)
               metlinks=Met_link.objects.filter(com2=p[i]).filter(com1=p[i+1]) #for reversible links
               for link in metlinks:
#                 e=pydot.Edge(link.com1.name,link.com2.name)
                 if not link.rea.reversibility:
                   e=pydot.Edge(link.com1.compoundid,link.com2.compoundid)
                   e.set_label(link.rea.reactionid)
                   e.set_URL("/kegg/rn/"+link.rea.reactionid)
                   Gd.add_edge(e)
            n=pydot.Node(p[-1]) #the last one
            n.set_URL("/kegg/cpd/"+p[-1])
            cn=Compound.objects.get(compoundid=p[i]).name
            n.set_tooltip(cn)
            Gd.add_node(n)
            Gd.write('c:/human/media/path.svg', prog="dot",format="svg")
            image=open('c:/human/media/path.svg',"rb").read()
            return HttpResponse(image, mimetype="image/svg+xml")
        else:
            err="the compounds are not in the network"
            return render_to_response('kpath.html', locals())

def shortpath(request): #avoid repeat reaction using breadth first search, paths as list of edges with rea data
#    from django.core.exceptions import ObjectDoesNotExist
    if request.method == 'GET':
      f = pathform(request.GET)
      if not f.is_valid():
           err="sth wrong"
           return render_to_response('kpath.html', locals()) #do sth else 
      else:
        c1id=f.cleaned_data["com1"]
        c2id=f.cleaned_data["com2"]
        G=request.session['mgraph']
        flag=0
        paths=[]
        if c1id in G and c2id in G:
            ns=[c1id]+G.neighbors(c1id)
            if c2id in ns:
              rs=G.get_edge_data(c1id,c2id).values()
              for r in rs:
                path=[[c1id,c2id,r['lable']]]
                paths.append(path)
            else:    
              ps=G.out_edges(c1id,data=True) #just use ps
              ps2=[]
              for p in ps:
                ps2.append([[p[0],p[1],p[2]['lable']]])  #change from a list of turple to a list of list
              while flag==0: #stop after find a path to c2, may be two or more paths
                newnodes=[] #for new nodes from all the existing nodes, while "newns" for new nodes from a specific node
                newps=[] #new paths to be found
                for p in ps2:
#                  newns=G.neighbors(p[-1][1])
#                  newnodes=newnodes+newns
                  newedges=G.out_edges(p[-1][1],data=True)
                  if newedges: #possible no out links
                    for ne in newedges:
                      r=ne[2].values()[0]
                      if not r==p[-1][2]:
                        if ne[1]==c2id:
                          path=p+[[ne[0],ne[1],r]] #list of list
                          paths.append(path)
                          flag=1
                        elif not ne[1] in ns: #neighbours may include nodes already found (loop)
                          newp=p+[[ne[0],ne[1],r]] #list of list
                          newps.append(newp)
                          if not ne[1] in newnodes:
                            newnodes.append(ne[1])
#                  if c2id in newns: #need to check, as maybe target in newns but not change flag as repeat rea. just do a through search
#                      rs=G.get_edge_data(p[-1][1],c2id).values()
#                      for r in rs:
#                        if not r['lable']==p[-1][2]:
#                          flag=1
#                          path=p+[[p[-1][1],c2id,r['lable']]] #list of list
#                          paths.append(path)
#                  else:
                ps2=newps
                ns=ns+newnodes #change ns after searching for all nodes to find multiple shortest paths 
            Gd=pydot.Dot()
            edges=[] #to avoid repeat edges
            nodes=[]
            for p in paths: #should keep rea info in paths, then will not need to search metlink again.
              for e in p:
                if not e in edges:
                  edges.append(e)
                  rea=Reaction.objects.get(reactionid=e[2])
                  edot=pydot.Edge(e[0],e[1],label=e[2],tooltip=rea.eq_in_id,labeltooltip=rea.equation)
                  edot.set_URL("/kegg/rn/"+e[2])
                  Gd.add_edge(edot)
                  if not e[0] in nodes:
                    nodes.append(e[0]) 
                    node=pydot.Node(e[0],URL="/kegg/cpd/"+e[0])
                    cname=Compound.objects.get(compoundid=e[0]).name
                    node.set_label(cname)
#                    node.set_tooltip(cname)
                    Gd.add_node(node)
#            nodes.append(c2id) 
            node=pydot.Node(c2id,URL="/kegg/cpd/"+c2id)
            cname=Compound.objects.get(compoundid=c2id).name
            node.set_label(cname)
#            node.set_tooltip(cname)
            Gd.add_node(node)
            Gd.write('c:/human/media/path.svg', prog="dot",format="svg")
            image=open('c:/human/media/path.svg',"rb").read()
            return HttpResponse(image, mimetype="image/svg+xml")
        else:
            err="the compounds are not in the network"
            return render_to_response('kpath.html', locals())

def testmenu(request):
    return render_to_response('mouseovermenu1.html', locals())
